﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using NetCommand.Web;

namespace NetCommand.Web
{
    public class WebMessageFactory
    {
        public static Dictionary<uint, Type> Msgtypes = new Dictionary<uint, Type>();
        public static void RegisterMessage()
        {
            registerMessage(typeof(LoginMessage));
        }
        public static void registerMessage(Type type)
        {
            WebMessage msg = Activator.CreateInstance(type) as WebMessage;
            if (msg != null)
            {
                Msgtypes.Add(msg.CLSID, type);  
            }
        }

        public static string SerializeMessage(WebMessage msg)
        {
            try
            {
                string message = "{\"Message\":";

                string data = JsonConvert.SerializeObject(msg);
                return message + data + "}";
            }
            catch (Exception ex)
            {
                return "";
            }
        }

        public static WebMessage DeserializeMessage(string message)
        {
            try
            {
                WebMessage msg = null;
                //message = "{\"Message\":{\"CLSID\":1,\"userName\":\"panqingyun\",\"passWord\":\"123456\"}}";
                if (message == "")
                {
                    return null;
                }
                JObject objJson = JObject.Parse(message);
                if(objJson == null)
                {
                    return null;
                }

                JToken value = objJson["Message"];
                uint ID = value.Value<uint>("CLSID");
                if (Msgtypes.ContainsKey(ID))
                {
                    Type msgType = Msgtypes[ID];
                    msg = (WebMessage)JsonConvert.DeserializeObject(value.ToString(), msgType);
                }

                return msg;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
    }
}
